package com.eurasia.assignment.service;

import java.util.List;
import java.util.Optional;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.eurasia.assignment.domain.User;
import com.eurasia.assignment.domain.UserRole;
import com.eurasia.assignment.infrastructure.repository.UserRepository;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }


    public boolean validateUser(String username, String password) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            return passwordEncoder.matches(password, user.getPassword()) && user.isEnabled();
        }
        return false;
    }
    
    public List<User> findAllUsers() {
        return userRepository.findAll();
    }
    
    /**
     * 删除指定ID的用户
     * @param userId 用户ID
     * @return 如果用户存在并成功删除返回true，否则返回false
     */
    public boolean deleteUser(Long userId) {
        if (userRepository.existsById(userId)) {
            userRepository.deleteById(userId);
            return true;
        }
        return false;
    }

    public User login(String username, String password, String role) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new AuthenticationException("用户名密码错误") {});

        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new AuthenticationException("用户名密码错误") {};
        }

        if (!user.getRole().toString().equals(role)) {
            throw new AuthenticationException("用户名密码错误") {};
        }

        return user;
    }

    /**
     * 获取所有学生用户
     * @return 学生用户列表
     */
    public List<User> findAllStudents() {
        return userRepository.findByRole(UserRole.STUDENT);
    }

    /**
     * 根据真实姓名查询学生
     * @param realName 真实姓名（支持模糊匹配）
     * @return 符合条件的学生列表
     */
    public List<User> findStudentsByRealName(String realName) {
        if (realName == null || realName.trim().isEmpty()) {
            return findAllStudents();
        }
        return userRepository.findByRoleAndRealNameContaining(UserRole.STUDENT, realName.trim());
    }
}